(function ($) {
    var defaults = {
        speed: 3000,
        url: '/batch/index/progress'
    };

    var getBatchId = function () {
        var batch_ids = localStorage.getItem('batch_ids');
        batch_ids = batch_ids ? JSON.parse(batch_ids) : {};

        var url = location.pathname.toLowerCase();
        var batch_id = batch_ids[url] ? batch_ids[url] : '';
        console.log(url, batch_id);
        return batch_id;
    };

    var delBatchId = function () {
        var batch_ids = localStorage.getItem('batch_ids');
        batch_ids = batch_ids ? JSON.parse(batch_ids) : {};

        var url = location.pathname;
        batch_ids[url] = '';
        localStorage.setItem('batch_ids', JSON.stringify(batch_ids));
    };

    var delBox = function () {
        $('.kc_progress').remove();
    }

    var showBox = function (title, info) {
        var box = $('' +
            '<div class="kc_progress" style="font-size: 12px; color:red;position: absolute;top: 15px;left: 35%;text-align: center;">' +
            '<img src="/Public/Wap/images/loading.gif" alt="">' +
            '<span style="margin-left: 5px">' + title + '</span>' +
            '<span style="margin-left: 5px">' +
            '<span class="pprogress">' + info + '</span>' +
            '</span>' +
            '</div>');

        if ($('.kc_progress').length) {
            delBox();
        }

        $(".content-header").append(box);
    };

    var checkStatus = function (data) {
        switch (data.status) {
            case 1://运行中
                showBox(data.title, data.info);
                break;
            case 2://成功
                delBatchId();
                alert(data.info);
                location.reload();
                break;
            case 0://无效的任务id
            case 3://失败
                delBatchId();
                delBox();
                alert(data.info);
        }
    };

    var run = function (options) {
        var batch_id = getBatchId();
        if (!batch_id) {
            setTimeout(function () {
                run(options);
            }, options.speed);
            return;
        }

        $.ajax({
            url: options.url,
            type: 'post',
            data: {batch_id: batch_id},
            dataType: 'json',
            success: function (data) {
                checkStatus(data);
            },
            complete: function () {
                setTimeout(function () {
                    run(options);
                }, options.speed);
            }
        });
    };

    $.fn.progress = function (options) {
        var options = $.extend(defaults, options);
        return this.each(function () {
            run(options);
        });
    }
})(jQuery);